from flask import Blueprint, request, render_template, redirect, session
from models import *
from werkzeug.security import generate_password_hash, check_password_hash

user = Blueprint("user", __name__)

def clacklogin(func):
    def inner(*args,**kwargs):
        if session.get("username"):
            return func(*args,**kwargs)
        else:
            return redirect("/login")
    return inner



@user.route("/reg", methods=["GET", "POST"])
def reg():
    username1 = User.query.all()
    if request.method == "GET":
        return render_template("reg.html")
    else:
        username = request.form.get("username")
        password = request.form.get("password")
        if username in username1:
            return redirect("/reg")
        else:
            user = User(username=username, password=generate_password_hash(password, method="pbkdf2:md5"))
            db.session.add(user)
            db.session.commit()
            return "注册成功"


@user.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        username = request.form.get("username")
        password = request.form.get("password")
        user = User.query.filter(User.username == username).first()
        if user and check_password_hash(user.password,password):
            session["username"] = username
            return redirect("/bookslist")
        else:
            return redirect("/login")

from flask_sqlalchemy import Pagination
@clacklogin
@user.route("/bookslist")
def bookslist():
    pag_num = int(request.args.get("pag_num",1))
    per_num = 3
    pagination = Books.query.paginate(pag_num,per_num)
    return render_template("bookslist.html",pages = pagination)

@user.app_template_filter("yuan")
def yuan(value):
    value = str(int(value) / 100) + "元"
    return value



@user.route("/deletebook")
@clacklogin
def deletebook():
    id = request.args.get("id")
    user = Books.query.get(id)
    db.session.delete(user)
    db.session.commit()
    return redirect("/bookslist")

@user.after_request
def after_request(response):
    url = request.url
    ret = ViewCount.query.filter(ViewCount.url == url).first()
    if ret:
        ret.count += 1
        print(url, ": ", ret.count)
    else:
        new_ret = ViewCount(url=url, count='1')
        db.session.add(new_ret)
        print('新的url访问')
    db.session.commit()

    return response